# -*- coding: utf-8 -*-
import scrapy
import base64
from urllib.parse import quote
from scrapy.utils.project import get_project_settings
from zc_core.model.items import Box
from zc_core.spiders.base import BaseSpider
from plap_zc.rules import *
from plap_zc.utils.login_selenium import SeleniumLogin


# Util.encrypt
class SkuSpider(BaseSpider):
    name = 'sku'
    customer = ''
    custom_settings = {
        'CONCURRENT_REQUESTS': 12,
        'CONCURRENT_REQUESTS_PER_DOMAIN': 12,
        'CONCURRENT_REQUESTS_PER_IP': 12,
    }
    # 本地商品报价链接
    sku_list_url1 = 'https://zc.plap.mil.cn/EpointMallService/rest/product_producttemp/getcansetprice'
    sku_list_url2 = 'https://zc.plap.mil.cn/EpointMallService/rest/product_producttemp/getpriceinfo'

    def __init__(self, customer=None, batchNo=None, *args, **kwargs):
        settings = get_project_settings()
        self.customer = customer
        if not customer:
            self.customer = settings.get('CUSTOMER', None)
        super(SkuSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        if not self.customer:
            raise Exception('请指定客户')
        self.size = 10
        self.cookie_dict = SeleniumLogin().get_cookies(self.customer)

    def _build_sku(self, page):
        return scrapy.FormRequest(
            url=self.sku_list_url1,
            method='POST',
            meta={
                'reqType': 'sku',
                'batchNo': self.batch_no,
                'page': page,
            },
            headers={
                "Host": "zc.plap.mil.cn",
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0",
                "Accept": "application/json, text/javascript, */*; q=0.01",
                "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
                "Accept-Encoding": "gzip, deflate, br",
                "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
                "X-Requested-With": "XMLHttpRequest",
                "Origin": "https://zc.plap.mil.cn",
                "Connection": "keep-alive",
                "Referer": "https://zc.plap.mil.cn/localprice.html",
                "Pragma": "no-cache",
                "Cache-Control": "no-cache",
            },
            formdata={"frameBodySecretParam": str(quote(str(base64.b64encode(quote(json.dumps({
                "cid": "", "xdproductcode": "", "productname": "", "brandname": "", "status": "0", "istuijian": "",
                "page": page, "size": self.size, "referer": "https://zc.plap.mil.cn/localprice.html"
            })).replace('%20', '').replace('/', '%2F').encode('utf-8')))[2:-1]).replace('%20', '').replace('/',
                                                                                                           '%2F'))},
            callback=self.parse_sku,
            errback=self.error_back,
            cookies=self.cookie_dict,
            priority=200,
        )

    def start_requests(self):
        # 品类、品牌
        yield self._build_sku(1)

    # 处理sku列表
    def parse_sku(self, response):
        meta = response.meta
        cur_page = meta.get('page')
        sku_list = parse_sku(response)
        for data in sku_list:
            yield scrapy.FormRequest(
                url=self.sku_list_url2,
                method='POST',
                meta={
                    'batchNo': self.batch_no,
                    'page': cur_page,
                    'item': data
                },
                headers={
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                formdata={"frameBodySecretParam": str(base64.b64encode(str(quote(json.dumps(
                    {"productguid": data.get('skuId'),
                     "referer": "https://zc.plap.mil.cn/localpricedetail.html?productguid={}".format(
                         data.get('skuId'))}))).encode(
                    'utf-8')))[2:-1]},
                callback=self.parse_skux,
                cookies=self.cookie_dict,
                errback=self.error_back,
                priority=200,
            )

        if cur_page == 1:
            totals = parse_totals(response, self.size)
            for page in range(2, totals + 1):
                if sku_list:
                    self.logger.info('清单2: page=%s' % (page))
                    yield self._build_sku(page)

    def parse_skux(self, response):
        meta = response.meta
        item = meta.get('item')
        sku = parse_skuxx(response, item)
        self.logger.info('清单1: count[%s]' % 1)
        sku_list = []
        sku_list.append(sku)
        yield Box('sku', self.batch_no, sku_list)
